package com.syyo.gulimall.ware.listener;

import com.rabbitmq.client.Channel;
import com.syyo.common.to.mq.OrderTo;
import com.syyo.common.to.mq.StockLockTo;
import com.syyo.gulimall.ware.service.WareSkuService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @Auther: wangzhong
 * @Date: 2020/7/30 10:54
 * @Description:
 */
@Slf4j
@Component
@RabbitListener(queues = "stock.release.stock.queue")
public class WareListener {

    @Autowired
    private WareSkuService wareSkuService;

    /**
     * 1）、下订单成功，订单过期或者手动取消，都要解锁库存
     * 2）、下订单成功，库存锁定成功，后面的业务失败，导致回滚
     */
//    @RabbitListener(queues = "stock.release.queue")
    @RabbitHandler
    public void unLockStockHandler(
            StockLockTo to,
            Message msg,
            Channel channel) throws IOException {

        System.out.println("===============订单过期，准备解锁库存===============");
        try {
            wareSkuService.unLockStock(to);
            channel.basicAck(msg.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception e) {
            // 发送请求失败,重新回队
            channel.basicReject(msg.getMessageProperties().getDeliveryTag(), true);
        }
    }

    @RabbitHandler
    public void closeOrderHandler(
            OrderTo to,
            Message msg,
            Channel channel) throws IOException {

        System.out.println("===============主动关闭，准备解锁库存===============");
        try {
            wareSkuService.unLockStock(to);
            channel.basicAck(msg.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception e) {
            // 发送请求失败,重新回队
            channel.basicReject(msg.getMessageProperties().getDeliveryTag(), true);
        }
    }
}
